package com.xiaoyu.servlet;

import com.xiaoyu.dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class updatePerson extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String phone = req.getParameter("phone");
        String reg= "^1[0-9]{10}$";
        if(!phone.matches(reg)){
            JOptionPane.showMessageDialog(null, "手机号有误", "格式输入错误", JOptionPane.ERROR_MESSAGE);
            resp.sendRedirect(req.getContextPath()+"/page.jsp");
        }else {
            String name = req.getParameter("name");
            String sex = req.getParameter("sex");
            String age = req.getParameter("age");
            System.out.println(123);
            String ids = req.getParameter("id");
            int ID = Integer.parseInt(ids);
            Connection conn = null;
            PreparedStatement pst = null;
            ResultSet rs = null;
            Object[] params ={name, sex, age, phone, ID};
            try {
                conn = BaseDao.getConnection();
                String sql = "update `contact` set `name`=?,`sex`=?,`age`=?, `phone`=? where ID=?";
                pst = conn.prepareStatement(sql);
                int i = BaseDao.execute(conn, sql, params, pst);
                if(i>0){
                    System.out.println("修改成功！");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                BaseDao.release(conn, pst, rs);
            }
            resp.sendRedirect(req.getContextPath()+"/page.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
